package initialization

import (
	"fmt"
	"ginweb-admin/commons/filter"
	"ginweb-admin/commons/middle"
	"ginweb-admin/global"
	"ginweb-admin/router"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"time"
)

// 初始化路由
func InitRouter() *gin.Engine {
	// 创建gin服务
	Router := gin.Default()
	// 提供服务组
	loginRouter := router.RouterGroupApp.Login.LoginRouter
	logoutRouter := router.RouterGroupApp.Logout.LogoutRouter
	codeRouter := router.RouterGroupApp.Code.CodeRouter
	videoRouter := router.RouterGroupApp.Video.VideoRouter
	sysUserRouter := router.RouterGroupApp.SysUser.SysUserRouter
	sysRoleRouter := router.RouterGroupApp.SysRole.SysRoleRouter
	sysUserRoleRouter := router.RouterGroupApp.SysUserRole.SysUserRoleRouter
	localUploadRouter := router.RouterGroupApp.LocalUpload.LocalUploadRouter
	sysMenuRouter := router.RouterGroupApp.SysMenu.SysMenuRouter
	sysRoleMenuRouter := router.RouterGroupApp.SysRoleMenu.SysRoleMenuRouter
	sysRoleAPiRouter := router.RouterGroupApp.SysRoleApi.SysRoleAPiRouter
	sysApiRouter := router.RouterGroupApp.SysApi.SysApiRouter

	// 解决跨域的问题
	Router.Use(filter.Cors())

	// 接口隔离
	publicGroup := Router.Group("/api")
	// 无需jwt拦截
	{
		loginRouter.InitLoginRouter(publicGroup)
		logoutRouter.InitLogoutRouter(publicGroup)
		codeRouter.InitCodeRouter(publicGroup)
		localUploadRouter.InitLocalUploadRouter(publicGroup)
	}
	// 需要jwt拦截
	privateGroup := Router.Group("/api/v1")
	// 只要是私有组的接口，全部使用jwt拦截
	privateGroup.Use(middle.JWTAuth()).Use(middle.CasBin_RABC())
	{
		videoRouter.InitVideoRouter(privateGroup)
		sysUserRouter.InitSysUserRouter(privateGroup)
		sysRoleRouter.InitSysRoleRouter(privateGroup)
		sysUserRoleRouter.InitSysUserRoleRouter(privateGroup)
		sysMenuRouter.InitSysMenuRouter(privateGroup)
		sysRoleMenuRouter.InitSysRoleMenuRouter(privateGroup)
		sysRoleAPiRouter.InitSysRoleAPiRouter(privateGroup)
		sysApiRouter.InitSysApiRouter(privateGroup)
	}
	fmt.Println("router register success")
	return Router
}

func RunServer() {
	// 初始化路由
	Router := InitRouter()
	// 为用户头像和文件提供静态地址
	// Router.StaticFS("/static", http.Dir("/static"))
	Router.StaticFS(global.Config.Local.StorePath, http.Dir(global.Config.Local.StorePath))
	// 获取配置文件的启动服务端口
	address := fmt.Sprintf(":%d", global.Config.Server.Port)
	// 启动HTTP服务
	s := initServer(address, Router)
	global.Log.Debug("服务启动成功：端口是", zap.String("port", address))
	// 保证文本顺序输出
	time.Sleep(10 * time.Microsecond)

	s2 := s.ListenAndServe().Error()
	global.Log.Debug("服务启动完毕", zap.Any("s2", s2))

}
